package com.wangp.mywrite.coding;

/***
 * @author wangpeng
 * @since 2022-02-25  15:45
 */
public class ComplexNumberMultiply {

    public String complexNumberMultiply(String num1, String num2) {
        String[] reals = num1.split("\\+");
        String[] virtuals = num2.split("\\+");

        String a = reals[0];
        String b = reals[1];
        String c = virtuals[0];
        String d = virtuals[1];

        return add(multiply(a, c), multiply(b, d)) + "+" + add(multiply(a, d), multiply(b, c));
    }

    private String add(String num1, String num2) {
        if (num1.contains("i") && num2.contains("i")) {
            String num1Str = num1.substring(0, num1.length() - 1);
            String num2Str = num2.substring(0, num2.length() - 1);
            int result = Integer.parseInt(num1Str) + Integer.parseInt(num2Str);
            if (result == 0) {
                return "0i";
            }
            return result + "i";
        } else {
            int result = Integer.parseInt(num1) + Integer.parseInt(num2);
            if (result == 0) {
                return "0";
            }
            return result + "";
        }
    }

    private String multiply(String num1, String num2) {
        if (num1.contains("i") && num2.contains("i")) {
            String num1Str = num1.substring(0, num1.length() - 1);
            String num2Str = num2.substring(0, num2.length() - 1);
            return Integer.parseInt(num1Str) * Integer.parseInt(num2Str) * (-1) + "";

        } else if (num1.contains("i") || num2.contains("i")) {
            if (num1.contains("i")) {
                num1 = num1.substring(0, num1.length() - 1);
            }
            if (num2.contains("i")) {
                num2 = num2.substring(0, num2.length() - 1);
            }
            return Integer.parseInt(num1) * Integer.parseInt(num2) + "i";
        } else {
            return Integer.parseInt(num1) * Integer.parseInt(num2) + "";
        }
    }

    public static void main(String[] args) {
        ComplexNumberMultiply complexNumberMultiply = new ComplexNumberMultiply();
        System.out.println(complexNumberMultiply.complexNumberMultiply("1+-1i", "0+0i"));
    }
}
